#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>
using namespace std;
void task1()
{
    cout << "task1*****" << endl;
}
void task2()
{
    cout << "task2*****" << endl;
}
void task3()
{
    cout << "task3*****" << endl;
}
typedef void (*pf_t)();
pf_t task[3] = {task1, task2, task3};
int main(int argc, char* argv[])
{
    pid_t id = fork();
    if(id < 0)
    {
        cout << "fork error" << endl;
    }
    else if(id == 0)
    {
        int cnt = 10;
        while(cnt)
        {
            cout << "i am child, pid:" << getpid() << "ppid: " << getppid() << " " << cnt-- << endl;
            sleep(1);
        }
        exit(10);
        //int* p = nullptr;
        //*p = 100;
        //execvp(argv[1], argv + 1);
    }
    else
    {
        int cnt = 5;
        while(cnt)
        {
            cout << "i am parent, pid:" << getpid() << " " << cnt-- << endl;
            sleep(1);
        }
        int status = 0;
        //阻塞等待
        //pid_t ret = waitpid(id, &status, 0);
        //pid_t ret = wait(nullptr);
        //if(ret > 0)
        //{
        //    printf("waitpid: %d, child_exit_signal: %d, child_exit_code: %d\n", id, status & 0x7f, status >> 8 & 0xff);
        //}
        //if(ret > 0)
        //{
           // if(WIFEXITED(status))
            //{
              //  cout << "wait success, child exit code : " << WEXITSTATUS(status) << endl;
           // }

        //}
        while(1)
        {

            pid_t ret = waitpid(id, &status, WNOHANG);
            if(ret == 0)
            {
                cout << "child running, .....\n";
                for(int i = 0; i < 3; i++)
                {
                    task[i]();
                }

            }
            else if(ret > 0)
            {
                cout << "wait success, child exit code: " << ((status >> 8) & 0xff) << "child exit signal" << (status & 0x7f) << endl;
                break;
            }
            else 
            {
                cout << "wait fail" << endl;
                break;
            }
            sleep(1);

        }
        sleep(5);
    }
}
